package com.springboot.myweb.config;


import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig  {

    //ShiroFilterFactoryBean(用户过滤)
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(@Qualifier("getDefaultWebSecurityManager") DefaultWebSecurityManager defaultWebSecurityManager){
        ShiroFilterFactoryBean FactoryBean = new ShiroFilterFactoryBean();
        //设置安全管理器
        FactoryBean.setSecurityManager(defaultWebSecurityManager);

        //添加shiro内置过滤器
        /**
         * anon:无需认证可访问
         * authc:必须认证才能访问
         * user:必须记住我才能使用
         * perms:拥有具体资源权限才能访问
         */
        Map<String, String> filterMap = new LinkedHashMap<>();

        //具体的拦截配置
        filterMap.put("/","anon");//根目录所有人都可以访问

        //想进login的只能是user用户且带有add权限，如果权限不够，跳转到专门的权限不够界面
        filterMap.put("/testshiro.html","perms[user:add]");
        FactoryBean.setUnauthorizedUrl("/404.html");

        filterMap.put("/index.html","authc");//登陆者访问

        FactoryBean.setFilterChainDefinitionMap(filterMap);

        //链接到我们定制的登录页面
        FactoryBean.setLoginUrl("/");

        return FactoryBean;
    }

    //DefaultWebSecurityManager(管理用户)
    @Bean
    public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm){
        DefaultWebSecurityManager webSecurityManager = new DefaultWebSecurityManager();
        //关联realm
        webSecurityManager.setRealm(userRealm);
        return  webSecurityManager;
    }

    //创建realm对象(链接数据)
    @Bean(name = "userRealm")
    public UserRealm userRealm(){
        return new UserRealm();
    }


    //整合shiro与thymemeaf
    @Bean
    public ShiroDialect getShiroDialect(){
        return  new ShiroDialect();
    }

}
